extends Reference


const FileUtil = preload("FileUtil.gd")


var _dir = Directory.new()
var _exclude_ : Dictionary = {}


##  添加排除的 Key
## @data  
func add_exclude(data):
	if data is Array:
		for i in data:
			_exclude_[i] = true
	else:
		_exclude_[data] = true
	return self


##  生成
func generate(scan_path: String) -> Script:
	if not _dir.dir_exists(scan_path):
		print_debug("要扫描的文件路径不存在！")
		return null
	
	var data = FileUtil.scan(scan_path, true)
	if data.size() > 0:
		var code = _format(_generate_code(data, scan_path))
		var script = GDScript.new()
		script.source_code = code
		return script
	return null


##  将代码格式
func _format(code: String) -> String:
	return """
############################################
#  [ 注意 ] 
# 这个文件是动态生成的，不要修改这个文件
# 否则手动修改的内容将不复存在
############################################

extends Reference

%s

""" % code


##  生成代码
## @data  文件路径数据
## @path  当前路径
## @indent  代码缩进
## @return  返回生成的代码
func _generate_code(data: Dictionary, path: String, indent: int = -1) -> String:
	indent += 1
	var code = ""
	var name_list = {}
	for file in data:
		# GD文件
		if !data[file] is Dictionary:
			var name = file.get_basename().replace(".", "_")
			if _exclude_.has(name):
				continue
			name_list[name] = true
			code += '{indent}const {name} = preload("{path}")\n'.format({
				indent = "\t".repeat(indent),
				name = name,
				path = path.plus_file(file)
			})
	
	for file in data:
		# 文件夹
		if data[file] is Dictionary:
			var name = file.capitalize()
			# 防止变量与类重名
			while name_list.has(name):
				name += "_"
			if _exclude_.has(name):
				continue
			name_list[name] = true
			code += "\n{indent}class {name}: \n".format({
				indent = "\t".repeat(indent),
				name = name,
			})
			"".capitalize()
			if data[file].size() > 0:
				code += _generate_code(data[file], path.plus_file(file), indent)
			else:
				# 如果没有子语句，则添加 pass
				code += "%spass" % "\t".repeat(indent)
	
	return code
